import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
export function useListComponent(props: any = {}) {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: 'stockGoodsCode',
      theadCode: 'selectgoodsinStockList', //basedatatable
      columnKey: 'specificationCode',
      isColumn: ['specificationCode', 'supplierName', 'goodsName', 'specificationName'],
      //表格-表头数据
      thead: [],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: '', // 关键字查询字段，空值表示查询全部
        likeWords: '', // 查询关键字，空值表示不进行过滤
        beginTime: '', // 查询时间范围起始值（建议格式：yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss）
        endTime: '', // 查询时间范围结束值
        onlySelf: 0, // 是否只查自己创建的数据：0 查所有；1 只查自己
        isShowDisabled: -1, // 是否显示禁用/作废数据：-1 所有；0 未作废；1 仅作废
        orderByFiled: '', // 排序字段名称，如 createTime、updateTime 等
        orderByType: 0, // 排序方式：0 倒序；1 升序
        onlyStocked: 0, // -1：显示全部、0：不显示0库存、1：仅显示0库存
        //差异
        goodsCode: '', // 基础物料编码
        supplierCode: '', // 供应商编码
        warehouseCode: '', // 仓库编码
        warehouseAreaCode: '', // 库区编码
        areaShelfCode: '', // 库位编码
        isDisable: 0, // 是否禁用：0未禁用；1已禁用，-1查询全部
        LastOutboundDateStart: '', // 最后出库日期
        LastOutboundDateEnd: '', // 最后出库日期
        CategoryCode: '', // 最后出库日期
      },
      //多选
      checkbox: {
        state: true,
        selectable: (row: any) => {
          return true;
        },
        list: [],
      },
      //表格-按钮数据
      btns: [
        {
          title: '导出数据',
          icon: 'Download',
          type: '',
          children: [
            {
              title: '导出当页数据',
              click: () => {
                setLoading('导出当页数据,请稍等');
                exportBtn(dataInfo.table.tbody);
              },
            },
            {
              title: '导出全部数据',
              click: () => {
                setLoading('正在导出全部数据,请稍等');
                proxy.$api.StockGoods.GetMatchPageStockGoodss({
                  ...dataInfo.table.search,
                  pageIndex: 1,
                  pageSize: 10000,
                  beginTime: dataInfo.table.search.beginTime || proxy.$getTimeAgo(1, 'years'), // 开始时间
                  endTime: dataInfo.table.search.endTime || proxy.$day(new Date()), // 结束时间
                })
                  .then((res: any) => {
                    exportBtn(res.list);
                  })
                  .catch(() => {
                    dataInfo.loading = false;
                  });
              },
            },
            {
              title: '导出选中数据',
              click: () => {
                setLoading('导出选中数据,请稍等');
                exportBtn(dataInfo.table.checkbox.list);
              },
            },
          ],
        },
      ],
      //表格-列表搜索
      operation: [
        {
          title: (row: any) => {
            return row.isUsed === 0 ? '编辑' : '查看';
          },
          click: (row: any) => {
            lookBtn(row);
          },
        },
        // {
        //   title: '删除',
        //   disabled: (row: any) => {
        //     return row.isUsed === 1;
        //   },
        //   click: (row: any, index: number) => {
        //     proxy.$messageBox('是否删除当前数据，请确认！', () => {
        //       proxy.$api.StockGoods.DeleteStockGoods({
        //         code: row.StockGoodsCode,
        //       })
        //         .then((res: any) => {
        //           proxy.$message(`删除成功`);
        //           getTbody();
        //         })
        //         .catch(() => {});
        //     });
        //   },
        // },
      ],
    },
  });
  const options: any = reactive({
    state: [
      {
        label: '待使用',
        value: 0,
        type: 'info',
      },
      {
        label: '已使用',
        value: 1,
        type: 'success',
      },
    ],
    onlyStocked: [
      {
        label: '全部',
        value: -1,
        type: 'info',
      },
      {
        label: '不显示',
        value: 0,
        type: 'success',
      },
      {
        label: '仅显示',
        value: 1,
        type: 'success',
      },
    ],
    //供应商
    supplier: [],
    //物料类型
    goodType: [],
  });
  // 查看
  const lookBtn = (row: any) => {
    proxy.$openPup(props.pup, 3);
    props.pup.form = {
      ...row,
      inventory: [],
      changeLog: [],
    };
    props.pup.loading = true;
    Promise.all([
      getInventory(), //修改产品信息
      getChangeLog(), //修改阶梯价信息
    ])
      .then((res: any) => {
        props.pup.loading = false;
      })
      .catch(() => {});
  };
  //获取库存
  const getInventory = (pup: any = props.pup) => {
    return new Promise((resolve, reject) => {
      proxy.$api.StockGoods.GetMatchPageStockGoodss({
        pageIndex: 1, //当前页码
        pageSize: 999, //每页显示数据的数量
        queryDataBaseFiled: 'specificationCode', // 关键字查询字段，空值表示查询全部
        likeWords: pup.form.specificationCode, // 查询关键字，空值表示不进行过滤
        supplierCode: pup.form.supplierCode,
        goodsCode: pup.form.goodsCode,
      })
        .then((res: any) => {
          pup.form.inventory = res.list.map((el: any) => ({
            ...el,
            rowClass: el.stockGoodsCode === pup.form.stockGoodsCode ? 'primary-row' : '',
          }));
          resolve(res);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };
  //获取变化明细
  const getChangeLog = (pup: any = props.pup) => {
    return new Promise((resolve, reject) => {
      proxy.$api.StockGoods.GetPageStockGoodsLog({
        ...pup.search,
        specificationCode: pup.form.specificationCode,
        stockGoodsCode: pup.form.stockGoodsCode,
      })
        .then((res: any) => {
          pup.form.changeLog = res.list.map((el: any) => ({
            ...el,
            productionDate: proxy.$day(el.productionDate),
            changeQuantiy: el.changeQuantiy === '-0' ? 0 : el.changeQuantiy,
            afterStockQuantity1: proxy.$count(`${el.afterStockQuantity || 0}-${el.changeQuantiy || 0}`),
          }));
          pup.search.totalCount = res.totalCount;
          resolve(res);
        })
        .catch((e: any) => {
          reject(e);
        });
    });
  };
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.StockGoods.GetMatchPageStockGoodss({
      ..._table.search,
    })
      .then((res: any) => {
        _table.tbody = res.list.map((el: any) => ({
          ...el,
          rowClass: el.changeQuantiy > 0 ? 'success-row' : '',
        }));
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 导出数据
  const exportBtn = (tbody: any[], thead?: any[]) => {
    proxy.$exportData(
      {
        thead: thead || dataInfo.table.thead,
        tbody: tbody,
        fileName: dataInfo.table.title,
      },
      dataInfo,
    );
    setTimeout(() => {
      dataInfo.loading = false;
    }, 1000);
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  onMounted(() => {});
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, getChangeLog, options };
}
